package cn.tedu.com.util;

import cn.tedu.com.bean.UserInfo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 *
 * </p>
 *
 * @author zhaoyue1
 * @Description
 * @since 2021-05-14
 */
public class AppUtil implements ApplicationContextAware {

    private static  ApplicationContext applicationContext=null;
    private static volatile   ThreadLocal<Map<String,Object>> THREAD_VAR=new ThreadLocal<>();
    private static final String USER_INFO="userinfo";
    public static final  String TOKEN="yhxxtoken";

    //本地线程添加变量
    public static void addValue(String name,Object obj){
        Map<String, Object> stringObjectMap = THREAD_VAR.get();
        if(Objects.isNull(stringObjectMap)){
            synchronized (THREAD_VAR){
                if(Objects.isNull(THREAD_VAR.get())){
                    Map<String,Object> localMap=new ConcurrentHashMap<>();
                    THREAD_VAR.set(localMap);
                    localMap.put(name,obj);
                }else{
                    Map<String, Object> localMap = THREAD_VAR.get();
                    localMap.put(name,obj);
                }
            }
        }else{
            stringObjectMap.put(name,obj);
        }
    }
    //本地线程获取变量
    public static Object getValue(String name) throws Exception {
        Map<String, Object> stringObjectMap = THREAD_VAR.get();
        if(CollectionUtils.isEmpty(stringObjectMap)){
            throw new Exception("本地变量尚未初始化");
        }
        Object o = stringObjectMap.get(name);
        return o;
    }
    //本地线程添加用户信息
    public static void  addUserInfo(UserInfo userInfo){
        addValue(USER_INFO,userInfo);
    }
    //从本地线程获取用户信息
    public static UserInfo getUserInfo() throws Exception {
        Object value = getValue(USER_INFO);
        if(Objects.nonNull(value)){
            return (UserInfo) value;
        }
        return null;
    }
    //存储token
    public static  void addToken(String token){
        addValue(TOKEN,token);
    }
    //过去token
    public static String getToken() throws Exception {
        Object value = getValue(TOKEN);
        if(Objects.nonNull(value)){
            return (String)value;
        }
        return  null;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext=applicationContext;
    }
}
